package com.jy.modules.cims.component.loan;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.FileUtils;
import com.jy.modules.cims.common.sysUtils.IFTPClient;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmLoanDetailService;
import com.jy.modules.cims.component.image.TransferImagesHelper;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmLoanDetailDTO;
import com.jy.modules.cims.data.dao.ImgurlDao;
import com.jy.modules.cims.data.dto.ImgurlDto;
import com.jy.modules.cims.sysUtils.ImgurFtpConfigInfo;

/**
 * @description 合作机构贷款影像文件处理服务组件
 * @version v1.0
 * @author shengzhoutao
 * @Date 2015-1-27
 */
@Service("com.jy.modules.cims.component.loan.CLoanImagesFileImpl")
public class CLoanImagesFileImpl {
	private static Logger logger = LoggerFactory.getLogger(CLoanImagesFileImpl.class);
	
	private String FTP_COMPRESSED_YES = "Y";

	@Autowired
	public ImgurlDao imgurlDao;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.loan.CLoanImpl")
	private ICLoan cLoan;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmLoanDetailService")
	private TCMmLoanDetailService tcmmLoanDetailService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.image.TransferImagesHelper")
	private TransferImagesHelper transferImagesHelper;

	/**
	 * @description 根据交易流水对象合同号处理影像文件。
	 * @param deal 交易流水对象,交易流水号必须输入
	 * @throws Exception
	 */
	public void transferImg(final TCMmCooperorgDealDTO deal) {
		String cooperorgCode = deal.getCooperorgCode();
		String dealCode = deal.getDealCode();
		String dealType = deal.getDealType();
		if (!SimpleStringUtils.hasText(dealCode)) {
			return;
		}
		logger.debug(CimsExceptionConstant.TRANSFER_IMG_DEAL_BEGIN, dealCode);

		try {
			// 根据交易流水号查询贷款明细关联的影像URL登记信息
			List<ImgurlDto> imgurlList = cLoan.searchUploadImgurlByDealCode(dealCode);
			if (CollectionsUtils.isEmpty(imgurlList)) {
				return;
			}
			
			List<ImgurlDto> newImgurlList = new ArrayList<ImgurlDto>();
			for (ImgurlDto imgurl : imgurlList) {
				imgurl.setDealCode(dealCode);
				imgurl.setCooperorgCode(cooperorgCode);
				imgurl.setDealType(dealType);
				
				newImgurlList.add(imgurl);
			}
			// 处理一个流水号下面所有的影像文件
			transferImg(newImgurlList);
			
			newImgurlList = null;
		} catch (Exception e) {
			logger.error(CimsExceptionConstant.TRANSFER_IMG_FAIL, e.getMessage());
			e.printStackTrace();
		}

		logger.debug(CimsExceptionConstant.TRANSFER_IMG_DEAL_END, dealCode);
	}

	/**
	 * @description 处理一个流水号下面指定的影像文件，所有文件正确处理完，更新贷款交互状态.
	 * @param imgurlList
	 *            影像文件集合 :ImgurlDto 对象的cooperorgCode, dealType, contractNo, attachUrl字段必须输入
	 * @throws Exception
	 */
	public void transferImg(List<ImgurlDto> imgurlList) throws Exception {
		Set<String> contractSet = new HashSet<String>();//
		List<String> successContractList = new ArrayList<String>();

		// 取影像URL登记信息的附件URL地址的文件
		for (ImgurlDto imgurl : imgurlList) {
			contractSet.add(imgurl.getContractNo());
		}

		String transFileStatus = CimsConstant.UPLOAD_FILE_FAIL;// 处理状态

		java.util.Iterator<String> iterator = contractSet.iterator();
		List<ImgurlDto> pendingList = null;
		while (iterator.hasNext()) {
			String contractNo = iterator.next();// 存放合同号
			// 待处理的影像文件
			pendingList = new ArrayList<ImgurlDto>();
			for (ImgurlDto imgurl : imgurlList) {
				if (contractNo.equals(imgurl.getContractNo())) {
					pendingList.add(imgurl);
				}
			}

			int pendingSize = pendingList.size();
			logger.debug("合同号:{},应处理文件个数:{}", contractNo, pendingSize);
			
			IFTPClient ftpClient = null;
			ImgurFtpConfigInfo imgurFtpConfigInfo = null;
			boolean createTempDirFlag = false;
			try {
				// 根据机构编号初始化获取影像FTP配置信息
				imgurFtpConfigInfo = transferImagesHelper.getImgurFtpConfigInfoByCpcBizLoanType(pendingList.get(0).getCooperorgCode(),pendingList.get(0).getDealType(),pendingList.get(0).getProductType(),pendingList.get(0).getContractNo());

				ftpClient = transferImagesHelper.getFTPClient(imgurFtpConfigInfo);
				// 登录FTP不成功直接返回
				if (!transferImagesHelper.loginFTP(ftpClient)) {
					return;
				}

				String localTmpPath = imgurFtpConfigInfo.getTmpFilePath() + pendingList.get(0).getDealType() + "/" + contractNo + "/";
				imgurFtpConfigInfo.setTmpFilePath(localTmpPath);
				
				// 创建临时文件目录
				transferImagesHelper.createTempDir(imgurFtpConfigInfo.getTmpFilePath());//
				createTempDirFlag = true;
				
				transFileStatus = transferImgByContractNo(ftpClient, contractNo, pendingList, successContractList, imgurFtpConfigInfo);

			} catch (Exception e) {
				logger.error(CimsExceptionConstant.TRANSFER_IMG_FAIL, e);
			} finally {
				// 退出FTP
				transferImagesHelper.logOutFTP(ftpClient);
				if(null != imgurFtpConfigInfo && createTempDirFlag){
					FileUtils.deleteDirectory(imgurFtpConfigInfo.getTmpFilePath());
				}
			}
			logger.debug("合同号:{},处理状态:{}",  contractNo, transFileStatus);
		}

		pendingList = null;
		successContractList = null;
		contractSet = null;
	}

	/**
	 * @description 根据合同号处理影像文件
	 * @param contractNo 合同号
	 * @throws Exception 
	 */
	@Async
	public void doTransferImgByContractNo(final String contractNo) throws Exception{
		TCMmLoanDetailDTO tcmmLoanDetailDTO = new TCMmLoanDetailDTO();
		tcmmLoanDetailDTO.setContractNo(contractNo);
		List<TCMmLoanDetailDTO> tcmmLoanDetailList = tcmmLoanDetailService.searchTCMmLoanDetail(SearchParamUtil.getSearchParam(tcmmLoanDetailDTO));
		tcmmLoanDetailDTO = null;
		if (CollectionsUtils.isEmpty(tcmmLoanDetailList)) {
			return;
		}
		tcmmLoanDetailDTO = tcmmLoanDetailList.get(0);
		
		ImgurlDto imgurlDto = new ImgurlDto();
		imgurlDto.setContractNo(contractNo);
		List<ImgurlDto> imgurlDtoList = imgurlDao.searchImgurl(SearchParamUtil.getSearchParam(imgurlDto));
		imgurlDto = null;
		
		logger.debug("流水号:{},合同号:{},处理文件个数:{}", tcmmLoanDetailDTO.getDealCode(), contractNo, imgurlDtoList.size());
		if (CollectionsUtils.isEmpty(imgurlDtoList)) {
			return;
		}
		
		
		List<ImgurlDto> pendingList = new ArrayList<ImgurlDto>();
		for(ImgurlDto dto:imgurlDtoList){
			dto.setCreditPackageName(tcmmLoanDetailDTO.getCreditPackageName());
			pendingList.add(dto);
		}
		
		IFTPClient ftpClient = null;
		ImgurFtpConfigInfo imgurFtpConfigInfo = null;
		boolean createTempDirFlag = false;
		try {
			// 根据机构编号初始化获取影像FTP配置信息
			imgurFtpConfigInfo = transferImagesHelper.getImgurFtpConfigInfoByCpcBizLoanType(tcmmLoanDetailDTO.getCooperorgCode(),null,null,null);

			ftpClient = transferImagesHelper.getFTPClient(imgurFtpConfigInfo);
			// 登录FTP不成功直接返回
			if (!transferImagesHelper.loginFTP(ftpClient)) {
				return;
			}

			String localTmpPath = imgurFtpConfigInfo.getTmpFilePath() + contractNo + "/";
			imgurFtpConfigInfo.setTmpFilePath(localTmpPath);
			// 创建临时文件目录
			transferImagesHelper.createTempDir(imgurFtpConfigInfo.getTmpFilePath());//
			createTempDirFlag = true;
			
			List<String> successContractList = new ArrayList<String>();
			String transFileStatus = transferImgByContractNo(ftpClient, contractNo, pendingList, successContractList, imgurFtpConfigInfo);
			
			logger.debug("流水号:{},合同号:{},处理状态:{}", tcmmLoanDetailDTO.getDealCode(), contractNo, transFileStatus);
		
			successContractList = null;	
			pendingList = null;
		} catch (Exception e) {
			logger.error(CimsExceptionConstant.TRANSFER_IMG_FAIL, e);
		} finally {
			// 退出FTP
			transferImagesHelper.logOutFTP(ftpClient);
			if(null != imgurFtpConfigInfo && createTempDirFlag){
				FileUtils.deleteDirectory(imgurFtpConfigInfo.getTmpFilePath());
			}
		}
	}
	
	/**
	 * 
	 * @param ftpClient
	 * @param contractNo
	 * @param imgurlList
	 * @param successContractList
	 * @param imgurFtpConfigInfo
	 * @return
	 * @throws Exception
	 */
	private String transferImgByContractNo(IFTPClient ftpClient,  final String contractNo, final List<ImgurlDto> imgurlList,
			List<String> successContractList, ImgurFtpConfigInfo imgurFtpConfigInfo) throws Exception {
		
		String transFileStatus = CimsConstant.DOWNLOAD_FILE_SUCCESS; //默认成功
		// 从url下载文件到本地
		boolean transFileflag = transferImagesHelper.downloadURLImg(imgurFtpConfigInfo, imgurlList);
		// 下载不成功
		if (!transFileflag) {
			transFileStatus  = CimsConstant.DOWNLOAD_FILE_FAIL;
			return transFileStatus;
		}

		String accessoryFtpUrl = "";

		// 如果上传压缩包影像文件
		if (FTP_COMPRESSED_YES.equalsIgnoreCase(imgurFtpConfigInfo.getFtpCompressed())) {
			String zipFileName = SimpleStringUtils.append(contractNo, ".zip");
			String zipDires = SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), contractNo);// 下载到当地那个路径下
			// 压缩一个合同号的影像文件
			boolean zipFile = transferImagesHelper.zipFile(zipDires, SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), zipFileName));
			if (zipFile) {
				String creditPackageName = imgurlList.get(0).getCreditPackageName();
				// 上传到文件服务器的路径
				String remoteDirectoryPath = SimpleStringUtils.append(imgurFtpConfigInfo.getFtpDir(),
						DateTimeUtils.formatDate(new Date(), DateTimeUtils.DEFAULT_DATE_FORMAT), "/", creditPackageName, "/");
				boolean uploadImg = ftpClient.uploadFile(new File(SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), zipFileName)),
						remoteDirectoryPath);
				if (uploadImg) {
					successContractList.add(contractNo);
					transFileStatus = CimsConstant.UPLOAD_FILE_SUCCESS;

					accessoryFtpUrl = remoteDirectoryPath + SimpleStringUtils.append(contractNo, "_ok.zip");
				} else {
					transFileStatus = CimsConstant.UPLOAD_FILE_FAIL;
				}
			}
		} else {
			int uploadSuccessCount = 0;
			for (ImgurlDto imgurl : imgurlList) {
				String[] attachUrlArray = imgurl.getAttachUrl().split("/");
				String remoteFileName = attachUrlArray[attachUrlArray.length - 1];
				String localDires = SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), contractNo, "/");
				String remoteDirectoryPath = SimpleStringUtils.append(imgurFtpConfigInfo.getFtpDir(), contractNo, "/");
				boolean uploadImg = ftpClient.uploadFile(new File(SimpleStringUtils.append(localDires, remoteFileName)), remoteDirectoryPath);
				if (uploadImg) {
					uploadSuccessCount++;
					transFileStatus = CimsConstant.UPLOAD_FILE_SUCCESS;

					accessoryFtpUrl = remoteDirectoryPath;
				} else {
					transFileStatus = CimsConstant.UPLOAD_FILE_FAIL;
				}
			}

			int pendingSize = imgurlList.size();
			if (uploadSuccessCount == pendingSize) {
				successContractList.add(contractNo);
				transFileStatus = CimsConstant.UPLOAD_FILE_SUCCESS;
			} else {
				transFileStatus = CimsConstant.UPLOAD_FILE_FAIL;
			}
		}

		// 修改贷款明细的状态发送请求查询
		if (CimsConstant.UPLOAD_FILE_SUCCESS.equals(transFileStatus)) {
			TCMmLoanDetailDTO tcmmLoanDetailDTO = new TCMmLoanDetailDTO();
			tcmmLoanDetailDTO.setContractNo(contractNo);
			List<TCMmLoanDetailDTO> tcmmLoanDetailList = tcmmLoanDetailService
					.searchTCMmLoanDetail(SearchParamUtil.getSearchParam(tcmmLoanDetailDTO));
			if (CollectionsUtils.isNotEmpty(tcmmLoanDetailList)) {
				for (TCMmLoanDetailDTO newTCMmLoanDetailDTO : tcmmLoanDetailList) {
					newTCMmLoanDetailDTO.setLoanEachStatus(CimsConstant.LOAN_EACH_STATUS_SEND);
					newTCMmLoanDetailDTO.setAccessoryFtpUrl(accessoryFtpUrl);
					newTCMmLoanDetailDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));
					tcmmLoanDetailService.updateTCMmLoanDetail(newTCMmLoanDetailDTO);
				}
			}
			tcmmLoanDetailDTO = null;
		}

		return transFileStatus;
	}

}
